package rs.udd.web.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import rs.udd.constants.UddMessages;
import rs.udd.exceptions.UddException;
import rs.udd.service.LinkService;
import rs.udd.web.binding.DateBinder;


@Controller
@RequestMapping(value = "/link")
public class LinkController {

	private static final Logger LOGGER = LogManager.getLogger(AdvertiserController.class);
	
	@Autowired
	LinkService linkService;
	

	@Autowired
	private DateBinder dateBinder;

	@InitBinder
	public void initBind(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, dateBinder);
	}
	
	@RequestMapping(value = "/confirmation", method = RequestMethod.GET)
	public String confirmEmail(HttpSession session, @ModelAttribute("random") String randomString, BindingResult result, Model model) throws UddException {		
		LOGGER.info("Confirmation link is clicked...");
		
		boolean successful = linkService.activateEmail(randomString);
		
		if (successful) {
			LOGGER.info("Email has been successfully changed.");
			model.addAttribute("message", "The email address has been successfully changed. Please login.");
			return "advertiser/linkSuccess";
		} else {
			LOGGER.info("The link has expired");
			model.addAttribute("message", UddMessages.ERROR_EXPIRED_LINK);
			return "error/error";
		}
		
	}
	
	@RequestMapping(value = "/advertiserRegistration", method = RequestMethod.GET)
	public String activateAdvertiser(HttpSession session, @ModelAttribute("random") String randomString, BindingResult result, Model model) throws UddException {		
		LOGGER.info("Advertiser registration confirmation link is clicked...");
		
		boolean successful = linkService.activateAdvertiser(randomString);
		
		if (successful) {
			LOGGER.info("Advertiser has been successfully activated.");
			model.addAttribute("message", "Your profile has been successfully activated. Please login.");
			return "advertiser/linkSuccess";
		} else {
			LOGGER.info("Advertiser activation unsuccessfull.");
			model.addAttribute("message", UddMessages.ERROR_ADVERTISER_ACTIVATION_UNSUCCESSFULL);
			return "error/error";
		}
		
	}

}
